package com.summer.media.controller;

import com.summer.commonException.XueChengException;
import com.summer.media.dto.QueryMediaParamsDto;
import com.summer.media.dto.UploadParamsDto;
import com.summer.media.dto.UploadResultDto;
import com.summer.media.pojo.MediaFiles;
import com.summer.media.service.MediaFileService;
import com.summer.model.PageParams;
import com.summer.model.PageResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@Slf4j
@Api(tags = "媒资文件管理API")
public class MediaFilesController {

    @Autowired
    private MediaFileService mediaFileService;


    @ApiOperation("媒资列表查询接口")
    @PostMapping("/files")
    public PageResult<MediaFiles> list(PageParams pageParams, @RequestBody QueryMediaParamsDto queryMediaParamsDto){
        Long companyId = 1232141425L;
        return mediaFileService.queryMediaFiels(companyId,pageParams,queryMediaParamsDto);
    }


    /**
     * 上传图片
     * @param file MultipartFile
     * @param objectName 指定上传文件的objectName，若不指定则按日期格式存入
     * @return MediaFilesDto
     */
    @ApiOperation("上传文件接口")
    @PostMapping(value = "upload/coursefile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public UploadResultDto uploadFile(@RequestPart("filedata") MultipartFile file,
                                      @RequestParam(required = false) String objectName){

        Long companyId = 1232141425L;
        // 文件名称
        String fileName = file.getOriginalFilename();
        if (StringUtils.isEmpty(fileName)){
            XueChengException.cast("上传文件失败，请重试");
        }
        // 文件大小
        long fileSize = file.getSize();
        // 文件类型
        String fileType = "001001";
        UploadParamsDto uploadParamsDto = new UploadParamsDto();
        uploadParamsDto.setFilename(fileName);
        uploadParamsDto.setFileSize(fileSize);
        uploadParamsDto.setFileType(fileType);

        String localFileName = null;
        try {
            File localFile = File.createTempFile("minio", "temp");
            localFile.deleteOnExit();
            file.transferTo(localFile);
            localFileName = localFile.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
            XueChengException.cast("上传文件到本地服务器临时文件失败");
        }
        return mediaFileService.uploadFile(companyId, uploadParamsDto, localFileName, objectName);
    }





}
